﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
using Microsoft.Practices.ObjectBuilder;
using Locator.Admin.Views;
using Microsoft.Practices.CompositeWeb;
using SignalR;
using SignalR.Hosting.AspNet;
using SignalR.Infrastructure;

namespace Locator.Admin
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
    public class ScannerService : IDisposable
    {
        // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
        // To create an operation that returns XML,
        //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     and include the following line in the operation body:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";

        public ScannerService()
        {
            WebClientApplication.BuildItemWithCurrentContext(this);
        }

        [CreateNew]
        public IAdminController AdminController { get; set; }

        [OperationContract]
        public void ScanStores()
        {
            IConnectionManager connectionManager = AspNetHost.DependencyResolver.Resolve<IConnectionManager>();
            var connection = connectionManager.GetConnection<Updates>();
            connection.Broadcast("Starting store scan");
            this.AdminController.ScanStores(connection);
            return;
        }

        [OperationContract]
        public void ScanProducts()
        {
            IConnectionManager connectionManager = AspNetHost.DependencyResolver.Resolve<IConnectionManager>();
            var connection = connectionManager.GetConnection<Updates>();
            connection.Broadcast("Starting products scan");
            this.AdminController.ScanProducts(connection);
            return;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
                if (AdminController != null)
                {
                    AdminController.Dispose();
                    AdminController = null;
                }
        }

        ~ScannerService()
        {
            Dispose(false);
        }
    }
}
